//
//  GradingTestSongAudioViewController.m
//  CommunityNannyO2O
//
//  Created by 90 on 15/7/21.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "GradingTestSongAudioViewController.h"
#import "AppConfig.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "MJExtension.h"
#import "AccountTool.h"
#import "JSDropDownMenu.h"
#import "GradingTestSongAudioTableViewCell.h"
#import "AudioDetailViewController.h"
#import "MJRefresh.h"
#import "UserDataSingleton.h"
#import "GradingTestSongAudioModel.h"
#import "GradingTestSongDetailModel.h"
#import "NIDropDown.h"
#import "MenuCell.h"
#import "AudioPlayViewController.h"
#import "NSString+Hash.h"
@interface GradingTestSongAudioViewController()<QXNetWorkToolDelegate,
        UITableViewDataSource,UITableViewDelegate,
        JSDropDownMenuDataSource,JSDropDownMenuDelegate,
        GradingTestSongAudioCellDeletage, NIDropDownDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *data;
@property (assign,nonatomic) int pageNum;
@property (copy,nonatomic) NSString *majorId;
@property (copy,nonatomic) NSString *gradeNum;
@property (nonatomic,weak) IBOutlet UIButton *button0;
@property (nonatomic,weak) IBOutlet UIButton *button1;

@property (strong, nonatomic) NIDropDown *dropDown;
@property (assign, nonatomic) BOOL isDropDown;

@property (nonatomic,weak) IBOutlet UIView *topView;

@property (nonatomic,strong) NSMutableArray *data1;
@property (nonatomic,strong) NSMutableArray *data2;

@property (nonatomic,assign) NSInteger selectIndex0;
@property (nonatomic,assign) NSInteger selectIndex1;

@property (nonatomic,assign) CGFloat cellHeight;

@property (nonatomic,strong) UIView *maskView;

@property (nonatomic,strong) GradingTestSongAudioTableViewCell *cell;

@property (nonatomic,strong) NSMutableArray * originArray;


@end


@implementation GradingTestSongAudioViewController

@synthesize data1;
@synthesize data2;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self configNavigationItem];
    
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    self.data = [[NSMutableArray alloc] init];
    
    [self configTopView];
    
    self.pageNum = 1;
    self.majorId = [UserDataSingleton shareInstance].currSelectExamKind;
    self.gradeNum = @"";
    
    self.cellHeight = 42;
    
    self.selectIndex0 = -1;
    self.selectIndex1 = -1;
    
    if (self.isFromDownLoad) {
      
        self.tableView.tag = 9990;
        
        [self loadLocalData];
        
    }else {
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    [self getData];

    }

}

-(void)setButtonTextBtn:(UIButton*)btn Title:(NSString*)title
{
    [btn setTitle:title forState:UIControlStateNormal];
}

-(void)configNavigationItem
{
    self.navigationItem.title = @"考级音频";
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar
     setBackgroundImage:[UIImage imageNamed:@"bg_navigation_bar"]
     forBarMetrics:UIBarMetricsDefault];
    
    //status bar的字体为白色
    //导航栏的背景色是黑色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],NSFontAttributeName,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
}


-(void)getData
{
    //[MBProgressHUD showMessage:@"正在加载" toView:self.view];
   
   
    
    [self.data removeAllObjects];
    
    NSString *pagenum = [NSString stringWithFormat:@"%d",self.pageNum];
    NSString *grade = self.gradeNum;
    if (self.gradeNum.length > 0)
    {
        grade = [self.gradeNum substringWithRange:NSMakeRange(0, 1)];
    }
    
    if (_isFromDownLoad) {
        
      
        
        [self loaclDataSequence:self.majorId grade:grade];
        
    }else {
    
        
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
        
    tool.QXNetWorkDelegate = self;

        
    [tool GetDataFromServerWithPostMethodandInterfaceName:GradingTestSongAudioInterface andParameter:
            @[@{@"major_id":self.majorId,
                @"grade_num":grade,
                @"nowpage":pagenum,
                @"pagesize":@"10"}] tag:1];

    }
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    if (Response == nil)
        return;
    
    NSString *message = Response;
    
    [MBProgressHUD showError:message toView:self.view];
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    NSString *mes = message;
    
    [MBProgressHUD showSuccess:mes toView:self.view];
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];

    switch (tag)
    {
        case 1:
        {
            for (NSDictionary *dic in Response)
            {
                GradingTestSongAudioModel *model = [GradingTestSongAudioModel GradingTestSongAudioWithDict:dic];
                
                [self.data addObject:model];
            }
            
            [self.tableView reloadData];
            
            break;
        }
        case 2:
        {
            for (NSDictionary *dic in Response)
            {
                GradingTestSongDetailModel *model = [GradingTestSongDetailModel GradingTestSongDetailWithDict:dic];
                
                AudioPlayViewController * obj = [AudioPlayViewController create];
                
                obj.songmodel = model;
                
                [self.navigationController pushViewController:obj animated:YES];
                break;
            }
            
            break;
        }
    }
}

#pragma mark 设置上下拉刷新

- (void)loadNewData
{
    [self.data removeAllObjects];
    self.pageNum = 1;
    
    [self getData];
    [self.tableView.header endRefreshing];
}

- (void)loadMoreData
{
    ++self.pageNum;
    
    [self getData];
    [self.tableView.footer endRefreshing];
}

- (IBAction)clickBtn0:(id)sender
{
    [self showMenu:0];
}

- (IBAction)clickBtn1:(id)sender
{
    [self showMenu:1];
}

-(void)configTopView
{
    self.data1 = [NSMutableArray arrayWithObjects:@"电吉他", @"电贝司",
                  @"爵士鼓",@"不限",nil];
    
    self.data2 = [NSMutableArray arrayWithObjects:@"1级", @"2级", @"3级", @"4级", @"5级", @"6级", @"7级", @"8级", @"9级", @"不限",nil];

    
    [self.topView setFrame:CGRectMake(self.topView.frame.origin.x,
                                     self.topView.frame.origin.y,
                                     [[UIScreen mainScreen] bounds].size.width,
                                      self.topView.frame.size.height)];
    
    self.dropDown = [[NIDropDown alloc]initDropDown:self.topView
                                                  X:0
                                                  Y:0
                                             Height:self.cellHeight * [self.data2 count]];
    
    self.dropDown.delegate = self;
    self.isDropDown = YES;
    
    //遮罩view
    self.maskView = [[UIView alloc] initWithFrame:
                     CGRectMake(0,
                                self.topView.frame.origin.y + self.topView.frame.size.height,
                                [[UIScreen mainScreen] bounds].size.width,
                                [[UIScreen mainScreen] bounds].size.height - self.topView.frame.origin.y - self.topView.frame.size.height)];
    
    self.maskView.hidden = YES;
    self.maskView.backgroundColor = [UIColor blackColor];
    self.maskView.alpha = 0.5;
    [self.view addSubview:self.maskView];
}

-(void)showMask
{
    self.maskView.hidden = NO;
}

-(void)hideMask
{
    self.maskView.hidden = YES;
}

-(void)showMenu:(NSInteger)column
{
    if (self.isDropDown)
    {
        CGFloat menuHeight;
        
        if (column == 0)
        {
            menuHeight = self.cellHeight * [self.data1 count];
        }
        else
        {
            menuHeight = self.cellHeight * [self.data2 count] - 200;
        }
        
        [self.dropDown setMenuHeight:menuHeight];
        [self.dropDown showDropDownOfColumn:column];
        [self showMask];
    }
    else
    {
        [self.dropDown hideDropDown];
        [self hideMask];
    }
    
    self.isDropDown = !self.isDropDown;
}

///////NIDropDown
- (NSInteger)NIDropDownNumberOfSectionsInTableView:(UITableView *)tableView Column:(NSInteger)column
{
    return 1;
}

-(NSInteger)NIDropDownTableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section Column:(NSInteger)column
{
    if (column == 0)
    {
        return [self.data1 count];
    }
    else {
        return [self.data2 count];
    }
    
    return 0;
}

- (CGFloat)NIDropDownTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath Column:(NSInteger)column
{
    return self.cellHeight;
}

- (UITableViewCell *)NIDropDownTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath Column:(NSInteger)column
{
    MenuCell *cell = [MenuCell cellWithTableView:tableView];
    
    NSMutableArray *ary;
    if (column == 0)
    {
        ary = self.data1;
    }
    else
    {
        ary = self.data2;
    }
    
    if ([ary count])
    {
        cell.infoLabel.text = [ary objectAtIndex:indexPath.row];
        
        if (column == 0)
        {
            if (self.selectIndex0 != -1 && self.selectIndex0 == indexPath.row)
            {
                cell.check.hidden = NO;
            }
        }
        else
        {
            if (self.selectIndex1 != -1 && self.selectIndex1 == indexPath.row)
            {
                cell.check.hidden = NO;
            }
        }
    }
    
    return cell;
}

- (void)NIDropDownTableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath Column:(NSInteger)column
{
    NSArray *array = [tableView visibleCells];
    
    for (MenuCell *cell in array)
    {
        cell.check.hidden = YES;
    }
    
    MenuCell *cell = (MenuCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell)
    {
        cell.check.hidden = NO;
    }
    
    if (column == 0)
    {
        self.selectIndex0 = indexPath.row;
        
        [self setButtonTextBtn:self.button0
                         Title:[self.data1 objectAtIndex:self.selectIndex0]];
        
        switch (indexPath.row)
        {
            case 0:
                self.majorId = [UserDataSingleton shareInstance].quiTa;
                break;
            case 1:
                self.majorId = [UserDataSingleton shareInstance].bass;
                break;
            case 2:
                self.majorId = [UserDataSingleton shareInstance].JazzDrum;
                break;
            case 3:
                self.majorId = @"";
                break;
        }
    }
    else if(column == 1)
    {
        self.selectIndex1 = indexPath.row;
        
        [self setButtonTextBtn:self.button1
                         Title:[self.data2 objectAtIndex:self.selectIndex1]];
        
        if (indexPath.row == ([self.data2 count] - 1))
        {
            self.gradeNum = @"";
        }
        else
        {
            self.gradeNum = [self.data2 objectAtIndex:indexPath.row];
        }
    }
    
    self.isDropDown = !self.isDropDown;
    [self hideMask];
    
    self.pageNum = 1;
    

    
    [self getData];
}


////////////tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.cell = [GradingTestSongAudioTableViewCell cellWithTableView:tableView];
    
    if (self.isFromDownLoad) {
        
        self.cell.isFromDown = YES;
    }
    
    if ([self.data count] > 0)
    {
        GradingTestSongAudioModel *model = (GradingTestSongAudioModel *)[self.data objectAtIndex:indexPath.row];
        
        self.cell.songId = model.id;
        
        self.cell.nameLabel.text = model.song_name;
        
        self.cell.detailLabel.text = model.song_brief;
        
        self.cell.testSongAudioModel = model;
        
        self.cell.gradingTestSongAudioCellDelegate = self;
    }
    
    return self.cell;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( self.tableView.tag == 9990) {
     
        
        NSUInteger row = [indexPath row];
        
        [self removeFile:row];
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationLeft];
    }
    

}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if ( self.tableView.tag == 9990) {
        
        
        return YES;
    }
    

    return NO;
    
}
/*此时删除按钮为Delete，如果想显示为“删除” 中文的话，则需要实现
 UITableViewDelegate 中的- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath方法*/

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return @"删除";
}

//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    JobListItem *item = [self.jobArray objectAtIndex:indexPath.row];
//    TCjobDetailViewController *jobDetailVC = [TCjobDetailViewController create];
//    jobDetailVC.JID = item.JID;
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    [self.tabBarController.navigationController pushViewController:jobDetailVC animated:YES];
//    
//}


-(void)useMethodToFindBlackLineAndHind
{
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    blackLineImageView.hidden = YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self configNavigationItem];

    [self useMethodToFindBlackLineAndHind];
    
    [self.tableView reloadData];
}

-(void)viewWillDisappear:(BOOL)animated
{

}

- (void)clickId:(NSString*)songId songModel:(GradingTestSongAudioModel *)model
{
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    if (!self.isFromDownLoad) {
       
        [MBProgressHUD showMessage:@"正在加载" toView:self.view];
        QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
        
        tool.QXNetWorkDelegate = self;
        
        [tool GetDataFromServerWithPostMethodandInterfaceName:GradingTestSongDetailInterface andParameter:@[@{@"song_id":songId}] tag:2];
    }else {
    
        
        GradingTestSongDetailModel * songModel = [[GradingTestSongDetailModel alloc]init];

        for (GradingTestSongAudioModel *audioModel in self.data) {
            
            if (audioModel.song_name == model.song_name) {
            
                songModel.song_name = audioModel.song_name;
                
                songModel.song_brief = audioModel.song_brief;
                
                songModel.song_url = audioModel.song_url;
                
                songModel.cover_img = audioModel.cover_img;
                
                songModel.isDownLoad = YES;
            }

        }
        
        AudioPlayViewController * obj = [AudioPlayViewController create];
        
        obj.songmodel = songModel;
        
        [self.navigationController pushViewController:obj animated:YES];
    
    }

}

- (void)loadLocalData{

    
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSString *plistName = @"download.plist";
    
    NSString *plistpath = [caches stringByAppendingPathComponent:plistName];
    
    NSArray * songArray  = [NSArray arrayWithContentsOfFile:plistpath];
   
    
    self.originArray = [NSMutableArray array];
    
    for (NSDictionary *dic in songArray) {
        
        GradingTestSongAudioModel *model = [GradingTestSongAudioModel objectWithKeyValues:dic];
        
        [self.data addObject:model];
        
        [self.originArray addObject:model];
    }
    
    [self.tableView reloadData];
}

- (void)loaclDataSequence :(NSString *)majorId grade:(NSString *)grade {

    NSMutableArray * NewArray = [NSMutableArray array];
    
    if ([grade isEqualToString:@""] && ![majorId isEqualToString:@""]) {
        
        for (GradingTestSongAudioModel *model  in self.originArray) {
            
            if ([model.major_id isEqualToString: majorId]) {
                
                [NewArray addObject:model];
                
            }
            
        }
        
        [self.data addObjectsFromArray:NewArray];
        
        [self.tableView reloadData];
        
        return;
    }
    
    if ([majorId isEqualToString:@""] && ![grade isEqualToString:@""]) {
        
        for (GradingTestSongAudioModel *model  in self.originArray) {
            
            if ([model.grade_num isEqualToString: grade]) {
                
                [NewArray addObject:model];
                
            }
            
        }
        
 
        [self.data addObjectsFromArray:NewArray];
        
        [self.tableView reloadData];
        
        return;
    }

    if ([majorId isEqualToString:@""] && [grade isEqualToString:@""]) {
        
         [self.data addObjectsFromArray:self.originArray];
        
        [self.tableView reloadData];
        
        return;
    }
    
    
    for (GradingTestSongAudioModel *model  in self.originArray) {
        
        if ([model.grade_num isEqualToString: grade] && [model.major_id isEqualToString: majorId]) {
            
            [NewArray addObject:model];
            
        }
        
    }
    
        [self.data addObjectsFromArray:NewArray];
    
        [self.tableView reloadData];
    
        return;
}


- (void)removeFile:(NSUInteger)index{

    GradingTestSongAudioModel * model  = self.data[index];

    [self.originArray removeObject:model];
    
    [self.data removeObject:model];
    
    NSMutableArray *  newArray = [NSMutableArray array];
    
    for (GradingTestSongAudioModel *model in self.originArray) {
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        
        dict[@"song_url"] = model.song_url;
        
        dict[@"id"] = model.id;
        
        dict[@"cover_img"] = model.cover_img;
        
        dict[@"song_name"]  = model.song_name;
        
        dict[@"song_brief"] = model.song_brief;
       
        dict[@"major_id"]= model.major_id;
        
        dict[@"grade_num"] = model.grade_num;
        
        [newArray addObject:dict];
    }
    
    
    NSString *Mp3fileName = [NSString stringWithFormat:@"%@.mp3", [model.song_name md5String]];
    
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSString *Mp3filepath = [caches stringByAppendingPathComponent:Mp3fileName];
    
    
    NSFileManager* fileManager=[NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:Mp3filepath]) {
        
        BOOL blDele= [fileManager removeItemAtPath:Mp3filepath error:nil];
    }

    NSString *plistName = @"download.plist";
    
    NSString *plistpath = [caches stringByAppendingPathComponent:plistName];
   
    if ([fileManager fileExistsAtPath:plistpath]) {
        
        [newArray writeToFile:plistpath atomically:YES];
    
    }
    

}

@end

























